#!/usr/bin/env python
# -*- coding: utf-8 -*-
# http://docs.python.org/whatsnew/pep-328.html
from __future__ import absolute_import
from __future__ import print_function   # deletes the print statement

import sys
from traceback import format_exception, format_exception_only
from cherrypy import request, response
from webpyte import ShowUserThisException

# Use simplejson or Python 2.6 json, prefer simplejson.
try:
    import simplejson as json
except ImportError:
    import json # http://docs.python.org/library/json.html
# The other modules can import json from this one.
json_encoder = json.JSONEncoder()


def as_json():
    def decorate(func):
        def wrap(*a, **kw):
            response.headers['Content-Type'] = 'application/json'
            try:
                result = func(*a, **kw)
            except Exception as e:
                #result = dict(success=False, error=str(e))
                result = dict(success=False,
                    error=''.join(format_exception(*sys.exc_info())))
            else:
                if isinstance(result, dict):  result['success'] = True
            return json_encoder.iterencode(result)
        wrap.__doc__ = func.__doc__
        return wrap
    return decorate


def is_ajax_request():
    '''Returns True if current request is ajax.'''
    return request.headers.get('X-Requested-With', '').lower() \
            == 'xmlhttprequest'

